﻿//*********************************************************************
//
//  文件名：OAuth2RefreshTokenProvider
//
//  作者： LW
//
//  作用：
//
//  日期：2015/9/8 16:17:09
//
//*********************************************************************
using System;
using Microsoft.Owin.Security.Infrastructure;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Framework.Common;

namespace Application.WebAPI.Provider
{
    /// <summary>
    /// OAuth2RefreshTokenProvider
    /// 刷新令牌
    /// </summary>
    public class OAuth2RefreshTokenProvider : IAuthenticationTokenProvider//AuthenticationTokenProvider
    {
        //用ConcurrentDictionary是为了线程安全
        private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();

        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            if (!context.OwinContext.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            }

            var guid = Guid.NewGuid().ToString("n");

            _refreshTokens.TryAdd(guid, context.Ticket);

            var client_id = context.Ticket.Properties.Dictionary["as:client_id"];

            context.SetToken(guid);

            SetCacheUserToken(guid, client_id);
        }

        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            AuthenticationTicket ticket;
            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                context.SetTicket(ticket);
            }
        }

        public void Create(AuthenticationTokenCreateContext context)
        {
            throw new NotImplementedException();
        }

        public void Receive(AuthenticationTokenReceiveContext context)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 设置缓存用户的token值
        /// </summary>
        /// <param name="token"></param>
        /// <param name="client_id"></param>
        public void SetCacheUserToken(string token, string client_id)
        {
            var user = RedisHelp.GetLoginUserCache(int.Parse(client_id));
            user.Token = token;
            RedisHelp.RefreshLoginUserCache(user);
        }
    }
}